/**
  @file
  @author Stefan Frings
*/

#include <QCoreApplication>
#include <QString>
#include "requesthandler.h"
#include "filelogger.h"
#include "staticfilecontroller.h"

#include "controller/dumpcontroller.h"
#include "controller/formcontroller.h"
#include "controller/fileuploadcontroller.h"
#include "controller/sessioncontroller.h"

using namespace Moolink;

/** Logger class */
extern FileLogger* logger;
extern StaticFileController* staticFile;

RequestHandler::RequestHandler(QObject* parent)
    :HttpRequestHandler(parent)
{}

void RequestHandler::service(HttpRequest& request, HttpResponse& response)
{
    QByteArray path=request.getPath();
    qDebug("Conroller: path=%s",path.data());

    // For the following pathes, each request gets its own new instance of the related controller.

    if (path.startsWith("/dump"))
    {
        DumpController().service(request, response);
    }

    else if (path.startsWith("/form"))
    {
        FormController().service(request, response);
    }

    else if (path.startsWith("/file"))
    {
        FileUploadController().service(request, response);
    }

    else if (path.startsWith("/session"))
    {
        SessionController().service(request, response);
    }
    else if (path.startsWith("/geturl"))
    {
        QString pathstr=path;
        QStringList dataPart=pathstr.split("/");
        //QString snm=station->getMN();
            // Set a response header
            response.setHeader("Content-Type", "text/html; charset=utf-8");

            // Return a simple HTML document
            response.write("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body>url:"+pathstr.toLatin1()+"<p>");
            response.write("站点编号MN:"+station.getMN().toLatin1()+"<p>");
            //response.write("站点密码PW:"+station->getPW().toLatin1()+"<p>");
            response.write("serialQuickCore服务己经运行,你可以尝试访问以下地址:<p><ul>");
            response.write("<li><a href=\"../\">本地服务:</a></li>");
            if(dataPart.count()>=3&&dataPart.at(2).size()==12) response.write("<li><a href=\"http://"+dataPart.at(2).toLatin1()+".hz.zjvo.cn:20080\">远程服务:</a></li>");
            response.write("</ul></body></html>",true);


    }
    else if (path.startsWith("/getdata"))
    {


            QString pathstr=path;
            QStringList dataPart=pathstr.split("/");
            QByteArray resp="[{}]";
            response.setHeader("Content-Type", "application/json; charset=utf-8");
            if(dataPart.count()>=3)
            {
                if(dataPart.at(2).startsWith("server"))
                {
                    if(dataPart.count()>=5)
                    {
                        if(dataPart.at(3).startsWith("index"))
                        {
                            resp=GetData::getJSON_Server(dataPart.at(4).toInt()).toStdString().data();
                        }
                    }
                    else
                    {
                       resp=GetData::getJSON_Servers().toStdString().data();
                    }
                }
                else if(dataPart.at(2).startsWith("device"))
                {
                    if(dataPart.count()>=5)
                    {
                        if(dataPart.at(3).startsWith("index"))
                        {
                            resp=GetData::getJSON_Device(dataPart.at(4).toInt()).toStdString().data();
                        }
                    }
                    else
                    {
                        resp=GetData::getJSON_Devices().toStdString().data();
                    }

                }

                else if(dataPart.at(2).startsWith("station"))
                {
                    resp=("["+JsonHelper::getJson(stationHW.stationInfo.data)+"]").toStdString().data();
                //resp=JsonHelper::getJson(sqldate->Query("select * from station")).toLatin1();
                }
                else if(dataPart.at(2).startsWith("emos"))
                {
                    resp=("["+JsonHelper::getJson(station.codeData05)+"]").toStdString().data();
                //resp=JsonHelper::getJson(sqldate->Query("select * from station")).toLatin1();
                }


            }
            response.write(resp,true);

    }
    else if (path.startsWith("/getserver"))
    {
        QString pathstr=path;
        QStringList dataPart=pathstr.split("/");
        //QString snm=station->getMN();
            // Set a response header
            response.setHeader("Content-Type", "text/html; charset=utf-8");

            // Return a simple HTML document
            response.write("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body>url:"+pathstr.toLatin1()+"<p>");
            response.write("站点编号MN:"+station.getMN().toLatin1()+"<p>");
            //response.write("站点密码PW:"+station->getPW().toLatin1()+"<p>");
            response.write("当前已配置的平台服务器:<p><ul>");
            for(int i=0;i<hostlist.getdata().size();i++)
            {
                response.write("<li>"+hostlist.getdata()[i].HostName.toLatin1()+"="+hostlist.getdata()[i].HostIp.toLatin1()+":"+QString::number(hostlist.getdata()[i].HostPort).toLatin1()+"</li>");
            }
            response.write("</ul></body></html>",true);
            stationHW.clickHostItem(0);
    }

    // All other pathes are mapped to the static file controller.
    // In this case, a single instance is used for multiple requests.
    else
    {
        staticFile->service(request, response);
    }

    qDebug("Conroller: finished request");

    // Clear the log buffer
    if (logger)
    {
       logger->clear();
    }
}
